package com.example.mvvm.base.vm.action;

import android.os.Bundle;


import androidx.fragment.app.Fragment;

import com.example.mvvm.base.data.SingleLiveEvent;
import com.example.mvvm.base.vm.ParameterField;
import com.example.mvvm.until.LogUtils;

import java.util.HashMap;
import java.util.Map;

public class FrameWorkModel implements ViewModeActivityManager {
    //跳转activity事件
    private SingleLiveEvent<Map<String, Object>> startActivityEvent;

    //跳转fragment
    private SingleLiveEvent<Map<String, Object>> startContainerActivityEvent;

    //结束页面
    private SingleLiveEvent<Void> finishEvent;

    public SingleLiveEvent<Map<String, Object>> getStartContainerActivityEvent() {
        return startContainerActivityEvent = createLiveData(startContainerActivityEvent);
    }

    public SingleLiveEvent<Map<String, Object>> getStartActivityEvent() {
        return startActivityEvent = createLiveData(startActivityEvent);
    }

    public SingleLiveEvent<Void> getFinishEvent() {
        return finishEvent = createLiveData(finishEvent);
    }

    private <T> SingleLiveEvent<T> createLiveData(SingleLiveEvent<T> liveData) {
        if (liveData == null) {
            liveData = new SingleLiveEvent<>();
        }
        return liveData;
    }

    /**
     * 关闭界面
     */
    @Override
    public void finish() {
        LogUtils.d("FrameWorkModel: finish");
        getFinishEvent().call();
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    @Override
    public void startActivity(Class<?> clz, Bundle bundle) {
        Map<String, Object> params = new HashMap<>();
        params.put(ParameterField.CLASS, clz);
        if (bundle != null) {
            params.put(ParameterField.BUNDLE, bundle);
        }
        getStartActivityEvent().postValue(params);
    }

    @Override
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }


    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     */
    @Override
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    @Override
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Map<String, Object> params = new HashMap<>();
        params.put(ParameterField.CANONICAL_NAME, canonicalName);
        if (bundle != null) {
            params.put(ParameterField.BUNDLE, bundle);
        }
        getStartContainerActivityEvent().postValue(params);
    }

    @Override
    public <T extends Fragment> void startContainerFragment(T fragment) {
        Bundle arguments = fragment.getArguments();
        startContainerActivity(fragment.getClass().getCanonicalName(), arguments);
    }
}